HELP
Richard Mansfield
Printing This Lesson
Select what you’d like to include when you print, and then click the Print Lesson button:
Text, images and activities (IE users only)
Text and images
Text only
Saving This Lesson
For instructions on saving this lesson (shown below), please select the browser you're using.
Introduction
Remember from Lesson 1 how crude XML looks if you simply hand it over to a browser with no explanation about how you want it formatted? Internet Explorer (IE) even displays the element tags!
Fortunately, there's a solution. You can create a special file where you specify style rules. And that's what we're going to talk about today.
In this lesson, you'll write a Cascading Style Sheets (CSS) file that tells a browser exactly how you want to present your recipes' titles and instructions to the user.
You'll learn how to use the CSS language—yes, another language. But it's a pretty simple language, focused on styling Web pages. You'll get the hang of it quite quickly. And then, you'll add another feature to the cookbook project. When the user clicks a recipe title in the listbox, you'll fetch that recipe's instructions and display them to the user!
Cascading Style Sheets, An Introduction
You can use Cascading Style Sheets (CSS) to specify how to format XML content. Remember that an XML document holds information, but it doesn't tell a Web browser (or any other application) how to present that information.
CSS is a great way to bring your XML data alive on a computer screen—exactly as you want it to look. For example, you can write a style sheet that says, "I want the recipe titles to be large, italic, and blue."
Let's give it a try. Follow these steps to create a simple CSS file:
title { font-size: x-large; font-style: italic; color: blue }
Following a selector is one or more property/value pairs. First you specify the property, then type a colon, then specify the value, and then complete the pair using a semicolon:
Whitespace in CSS
Browsers ignore any whitespace—tabs, blank lines, multiple space characters—in your CSS code. So you could just as easily write the above CSS code like this if you wish:
title {font-size: large;font-style: italic;color: blue;}
Most programmers agree that putting each style on its own line is easier to read and modify, particularly if the styles become complicated. But suit yourself. The browser won't care at all!
Okay, now all that's left to do is to open your recipes.xml file and add a reference to the CSS file. A reference tells the browser where to find the CSS file. The browser can then read and apply your style rules to the XML document.
Here's how to tell IE or any other application that will display the recipes where to find the associated CSS file:
<?xml-stylesheet type="text/css" href="Cookbook CSS Stylesheet.css"?>
The stylesheet and type terms in this code are standard, so you can use them without worrying about what they mean.
The meat of this code is the href (location) that tells a browser where to find the CSS style sheet. You don't have to include the entire filepath (C:\XML Projects\Cookbook) because you saved the .css file in the same directory as the .xml file it works with. All you need to provide is the name of the .css file: Cookbook CSS Stylesheet.css.
Watch here as I show you how to do this:
We're going to put a link into the recipes.xml file, a reference that describes where to find the CSS style sheet that we just created in our lesson. So double-click recipes.xml to open it in Visual Studio. Now create a blank line where we'll put the reference line by moving the blinking insertion cursor down one line to line 2, and then pressing Enter to create the blank line.
Now, move your insertion cursor back up to line 2. Press Control, V to paste the reference line that you just copied from the lesson, and now you're all set. Just press Control, S and save this XML file.
Notice that the reference doesn't contain a file path. It doesn't say C:\finished projects or anything like that. It doesn't have any file path. All it has is the name of the CSS file. We can do that because when we're looking in the file explorer, you'll notice that the recipes.xml file is in the same subdirectory as the Cookbook CSS file. That's the reason we don't need to provide any path. They're in the same folder
END TRANSCRIPT
Everything is ready now. So let's go ahead and test the styling. Right-click recipes.xml in Windows Explorer, and click Open With > Internet Explorer in the context menu. You'll see these results:
It works! This is better than just a continuous, wall-to-wall chunk of text where you can't tell the difference between titles and instructions. This large, blue typeface makes it clear where each recipe starts.
But as a Web page, this still isn't all that great. We can do better.
Experimenting With CSS Formats
Let's start by improving the typeface on the titles. For one thing, designers rarely use italics in headlines. Typefaces—how text characters look—divide into two main categories: serif and sans-serif.
These days, titles and headlines are usually in simple sans-serif typefaces, rather than the flowing italics we used for the titles. For body text in books, designers often use serifs. But we treat text on computer screens differently than in books. For online content, we tend to use sans-serif for both headers and body text. This is easier to read on screens.
In any case, let's use a sans-serif font-family property to display our titles in a more assertive style. Also, for readability, let's break up the elements by centering each title and separating the titles and instructions with a little bit of whitespace.
Here's how to modify the Cookbook CSS Stylesheet.css file to make these changes:
title { font-size: x-large; color: blue; display: block; font-family: Helvetica, Arial, sans-serif; font-weight: bold; text-align: center }
Good work. Now, here's how the changes we made to the style sheet improve the formatting:
So a block does two things. First, it inserts a blank line before and after an element, and then it renders the content wide enough to fully fill whatever container holds the element.
Courier looks like old-fashioned typewriter characters.
ARIAL LOOKS PLAIN AND SIMPLE.
Old English Text is gothic, ornate, and popular among the tattooed.
Because browsers don't all have the same typefaces, you can list your preferences in order. (In the example .css file above, we listed Helvetica as our first preference. But if the browser doesn't have that one available, Arial was listed as our second choice, and sans-serif our third choice.)
I like the extra-large size and the blue color, but you can of course change any of these rules to suit your personal style. You might prefer, for example, color: salmon or lightblue, or you could go hog-wild with DarkKhaki and font-weight:900!
Okay, next up, let's look at margins.
Adding Margins
Even though the block value added some whitespace between titles and instructions, how about also adding whitespace on the sides? It looks odd to have no margins—to have the instructions butting up against the left and right sides of the browser. The margin-left and margin-right properties will fix that.
And while we're at it, let's also use the margin-bottom property to visually separate each recipe from the recipe that follows. This is yet another way that whitespace can help the reader to quickly see the various units of text and their relationships.
Follow these steps to add margin rules to your style definition:
title { font-size: x-large; color: blue; display: block; font-family: Helvetica, Arial, sans-serif; font-weight: bolder; text-align: center } instructions { display:block; margin-left: 5%; margin-right: 5%; margin-bottom: 4%; }
Nice. Now each title-instruction pair forms a visual unit—one complete recipe. You can also add a margin-top rule to add whitepace above the instructions if you want to. But I think it looks best to have each recipe's title and instructions grouped close together.
CSS includes lots of ways to position and size blocks of text. Can you guess how to modify your .css file to position the titles 2% from the left side of the browser window? Click the button below to see the solution.
Let's Chat!
What do you like better—left-justified titles? Or centered titles? Voice your preference in the Discussion Area. A lot of us are learning XML so we can be in control of our own designs, so let's get a lively discussion going about this!
Absolute vs. Relative Values in CSS
Let's take a few minutes to talk about how we specify the size of elements in a browser. There's a reason that we've used percentages to specify the width of the margins in this lesson's examples. Margins describe spacing—how far in from the sides of their containers to place the title and instruction blocks. Essentially, we're describing length.
But percentages aren't the only option. We can also specify height, location, length, and other CSS properties using a variety of values, such as points, pixels, larger, centimeters, inches, percentages.
In many cases, percent is a good choice because it's a relative (changeable) value rather than an absolute (fixed) value. Think of relativity as saying, "Better wear enough clothes to stay comfortable," instead of the absolute statement, "Always wear two sweaters and an overcoat."
You get the idea. A relative approach takes context into account, making the decision appropriate to the circumstances—whereas, absolute is inflexible.
Absolute values can become a problem when you create a CSS style rule, because browsers don't have a standard, predictable width or height. Another way to think about width and height is aspect ratio, which is the relationship between width and height—or in other words, the shape (square or rectangular). The user might drag the browser, making it quite wide but not very high—creating an odd and unpredictable aspect ratio.
Even more of a problem is that screen sizes can differ so greatly. Imagine the bad result if you specified that a title should be 3 inches from the left side of the screen, but the screen was only a 2-inch wide cellphone!
Is the value absolute or relative?
Absolute specs can work okay with paper. Many book designers specify type sizes in points. A point is an absolute length: 1/72 of an inch. Using absolute values for a book can work just fine—after all, readers can't shrink or stretch a book. And readers hold a book a predictable distance from their eyes.
But this isn't true of browsers that people can resize. Similarly, it isn't true of screens that people can view up close (cellphone ), or at arm's length (monitors), or further away (TV).
In the digital world, things like length and aspect ratio are quite changeable. Someone could display your cookbook on one of those new postage-stamp size wristwatch screens, or perhaps on the jumbo 20,633-square-foot screen at Texas Motor Speedway.
Inches then (and other absolute specifications such as centimeters, millimeters, and points) aren't a great idea when specifying formatting for screens.
Let's see what happens when you specify an absolute margin, but then the user stretches the browser, throwing off your intended layout. Say that you want the title to align with the left side of the instructions. You fiddle around with the values, watching the effect in your browser until you figure out that a margin-left: 8%; for the title and a half-inch for the instructions line them both up correctly. Here's the code:
title { font-size: x-large; color: blue; display: block; font-family: Helvetica, Arial, sans-serif; font-weight: bolder; margin-left: 8%; } instructions { display:block; margin-left: .5in; margin-right: 5%; margin-bottom: 4%; }
But this alignment depends on the unlikely event that a user's browser and screen size will be identical to yours. If a user stretches the browser or tries to view your text in a cellphone, that will throw off the alignment—and your intended formatting is ruined.
Clearly, using absolute values like inches (the margin-left: .5in) is a bad idea when formatting for a screen. To solve this problem, make both the title and instructions margin-left values relative percentages. In other words, change the half-inch absolute value for the instructions element to the same 8% value used by the title element, like this:
instructions { display:block; margin-left: 8%; margin-right: 5%; margin-bottom: 4%; }
How About Pixels?
Why not specify length using pixels, you might ask? Excellent question.
Like percents, pixels are widely used to specify length in CSS. Pixels are those little dots of light you can see when you get really close to a TV, tablet, or other screens. Unlike inches, pixels vary in size based on how big a screen is. On a huge sports arena screen, pixels can be as big as bricks. On an iPhone, the pixels are so small, you can't see them. (Apple calls its screens retina, because the pixels are so dense that the human eye can't see them.)
Specify length in pixels, and you can be sure that your text or graphics content will position and align correctly, no matter what type of screen somebody uses to view your content.
The Programmer's Experiment Cycle
We've been going back and forth between saving a modification to the .css file and then seeing the results by switching to the IE browser and pressing F5 to refresh the page. Programmers often go through similar steps as they write code. In this lesson, you've seen how to use Notepad to modify a .css file and then test the modification like this:
When you program in VB, the experiment cycle is even simpler and more efficient, because the VB editor itself can simulate running the program you're working on (so you don't have to use the ALT + TAB shortcut to switch between programs):
The programmer's testing cycle is an efficient way to make a change in the code and then see the result immediately of that change. Let's see how that works. Here we've defined blue as the color for the title in Internet Explorer when we display our recipes.xml file. So we have a CSS style sheet here. We can make a change. Let's try changing the color from blue to red and see if we like that result.
Okay. You just make the change in the source code and then you save the file to overwrite the existing file. We'll just press . . . Control, S is a quicker way to do that than using the menu, so you'll get used to pressing Control, S to save the source, and then switching over to the program and pressing F5 to refresh. F5, the Function 5 key in most programs. We'll go back to the original and see if any changes have been made in that original. So we'll press F5, and there it goes. It changes immediately to red.
Let's try another one. Let's change it from centered to left-aligned. Just put in here "left" and press Control, S to save that. Press Alt, Tab to switch back to Internet Explorer, and press F5. And there we go. It changed from blue, centered to red, left.
Just remember the shortcut keys and you'll be flying back and forth between your code and seeing the result of the code. Press Control, S to save the code file. Press Alt, Tab to switch back to the program itself, and then press F5 to refresh the program and see the changes that you've made.
Web pages are filled with blocks containing various elements. And specifying the position and size of these blocks of content can become quite complex. Advanced CSS designers use interacting properties such as padding and borders.
But for our simple recipe formatting, we'll stick to using margins and percents for the margin values: margin-left: 8%;
The Vast World of CSS
What else can you do with CSS properties? Quite a lot. The current specification of CSS includes dozens of properties, ranging from common ones like color to rarities like text-indent (margins work better). And of course, most of these properties have many possible values. For example, the color property offers 140 named colors including PapayaWhip and OldLace. (See the Supplementary Material section for a link to the complete list, including color swatches so you can see what you'll get!)
Even though CSS is fairly easy to use, it's quite vast. In fact, we have an entire course just on CSS! We've really only explored a tiny area of a huge landscape, but you now understand the main ideas—how to punctuate the CSS property/value pairs, how to attach a CSS file to the XML file it supports, and how to use the efficient experiment cycle technique.
Displaying Instructions in the Cookbook Program
Now, let's switch gears from CSS browser programming and add another feature to the cookbook project.
In our last lesson, you added code to the Cookbook program's Form_Load event that fills a listbox with the titles of all your recipes. Now you'll write some programming that reacts when the user clicks one of those titles in the listbox. This new code will display the clicked recipe's instructions.
Where should you put the new code? The user clicks a title in the listbox, so it makes sense to put the code inside the listbox's Click event.
If you thought it was impressive that it only took 15 lines of code in Lesson 3 to open the XML document and fill the listbox with titles, wait until you see how much you'll accomplish now with three lines of code!
But before writing the code, you need to add a textbox control to your form that will display a recipe's instructions. Let's do that first.
Great. Now you're ready to add your programming code to the listbox's Click_Event.
Private Sub lstTitles_Click(sender As Object, e As EventArgs) Handles lstTitles.Click End Sub
Private Sub lstTitles_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstTitles.SelectedIndexChanged End Sub
It's not essential that you delete this unused sub. It won't do any harm when the program runs, because it contains no code. It does nothing. But while you're writing code, this empty event is debris—just distracting. So it's best to remove it.
Private Sub lstTitles_Click(sender As Object, e As EventArgs) Handles lstTitles.Click Dim IndividualRecipe As XmlNode IndividualRecipe = doc.SelectSingleNode("descendant::recipe[title='" & lstTitles.SelectedItem & "']") txtInstructions.Text = (IndividualRecipe.LastChild.InnerText) End Sub
Excellent work!
Beware of Word Wrap
Sometimes a line of code is quite long—too long to display on a single line in the editor. So the editor "wraps" part of the line down onto a second line. Unless your code window is really wide, it's possible that this line will "word wrap" on your monitor and appear as two lines:
IndividualRecipe = doc.SelectSingleNode("descendant::recipe[title='" & lstTitles.SelectedItem & "']")
But this is still only one line of code!
The editor will let you know when a line wraps by displaying a curved green arrow on the right side of the Code window, like this:
VB executes code line by line, as if it were a numbered list of tasks you want VB to perform. If you see the green arrow, be sure you don't press the ENTER key to break this long line into two lines! Instead, maximize the editor (click the maximize icon at the top right of the VS window) so the code has enough room to show up as a single line.
Looking at the Code Line by Line
All right, let's look at this code one line at a time. It's pretty amazing. It does an awful lot in those three lines. And one of the lines is just a simple Dim variable declaration.
The first line of code names an object variable, which I decided to call IndividualRecipe.
Dim IndividualRecipe As XmlNode
In the next line, this object variable will be given a copy of the instruction element that matches whatever title the user clicked. (Remember, for our purposes, node is just another word for element.)
This line of code is your first exposure to XPath, the language XML uses to search documents. We'll talk more about this later in the course, but for now, here's all you need to know:
The XPath code line first looks in the doc (our recipes.XML file) to find the title the user clicked (lstTitles.SelectedItem). Then XPath copies that entire recipe element and stores it in the IndividualRecipe variable.
You remember our old friend doc, don't you? When your program first starts running (up in the Form_Load event), doc is given a copy of the recipes.xml file. Now here in this XPath line of code, we're searching through doc to fetch the recipe the user wants to see.
The last code line just copies the instructions into the textbox:
txtInstructions.Text = (IndividualRecipe.LastChild.InnerText)
Recall that InnerText means the contents of an element (its data stripped of its tags). And because our recipe elements have two child elements (<title> and <instructions>), the LastChild element is the instructions.
One Last Thing . . .
We have one more small job to do. As is, the program works fine: When the user clicks a title, its instructions show up in the textbox. Try it by pressing F5 to test the program. Do you see the one thing you might want to improve?
When the program first runs, no instructions show up in the textbox because the user hasn't clicked a title yet. It makes more sense to the user—it's better UI design—if he or she can see instructions for the first recipe. You don't want to begin your program with a big, blank textbox. Some users might start typing into it!
To display the instructions, all you have to do is simulate the user clicking the listbox by adding two lines to the end of the Form_Load event:
The first new line selects the first title, and then the second line just triggers the listbox's Click event—same as if the user had clicked it. This second line shows you how you can execute one sub from another.
If you haven't already added these two lines to your cookbook program, go ahead and do it now!
Worry Not!
Remember, you don't need to memorize this code. If you ever need to do this job—fetch the contents of a specific element from an XML document—this code shows one way do it. To reuse this code, just change the variable names to whatever names you're using in your new program.
Or you can Google for something like vb get a specific element from an XML document. Google will list various code examples showing a variety of different ways to accomplish this task. Some of them will be the same approach we're using here in the cookbook program. Use whatever works or whatever approach appeals to you.
By the way, when you're Googling for example code, it's best to put vb right at the start of your search phrase to eliminate example code written in other programming languages!
You did it! Let's meet in Chapter 5 for a quick wrap-up.
Summary
Great job! You now have a solid foundation in CSS. You learned how to make XML content look good in browsers and other applications. You transformed raw XML data into attractive, readable text blocks. You saw how to link an XML file to the CSS file that formats it. And you practiced creating style rules using correct CSS punctuation, property/value pairs, and relative length values.
Beyond that, you tested your style rules by employing the programmer's experiment cycle—switching back and forth between modifying CSS styles in Notepad and then seeing the effect in Internet Explorer.
Here's your challenge for this lesson:
See if you can modify the Cookbook CSS Stylesheet.css file to add quite a bit of whitespace between the recipes. Try changing one of the style rules so the document looks something like this in IE:
In the next lesson, we'll be exploring XSL. It not only formats XML documents like CSS, but it can actually transform them!
Here you'll find good descriptions and examples of all the CSS properties, organized into categories such as layout, list, and typographical.
This handy reference shows all 140 named colors that all browsers will correctly display. Here's where you go when you want to choose a CSS color value!
Q: Is CSS used with VB programming? Or just with browsers?
A: CSS works with browsers. Compared to CSS, VB programming allows you much greater control over how you format your data and your UI. This is because you design and build VB programs from the ground up.
Displaying XML in a browser is different than displaying it in your own programs like the cookbook project. Chapters 2 and 3 in this lesson are all about using CSS to format data so it looks the way you want it to in a browser. But you don't use CSS with ordinary VB programs.
Remember that you can't modify a browser. A team at Microsoft wrote the IE browser program, and a team at Google wrote Chrome. And in each case, when they finished writing their browser, they closed its doors and sealed it off. You get to use their browser, but they don't give you the browser's code so that you can modify it.
The most you can do to influence how browsers format data is to write style rules using a language like CSS. You filter your raw XML through a CSS style sheet, causing the browser to ignore its default presentation rules and show the contents according to your rules. But you're not changing the browser's actual code.
By contrast, when you write your own programs, you're in complete control. Instead of writing CSS rules, you add VB controls like listboxes and textboxes to your program. And you can easily modify your program's presentation and behavior in several powerful ways:
Q: What does cascading mean in Cascading Style Sheets?
A: I was afraid some sharp student would ask this. For simple tasks like displaying your cookbook in a browser, the semi-advanced cascade technique doesn't matter. But if you're curious, cascading handles conflicting style rules. For example, say that a style sheet specifies that a title element's text should be blue, but elsewhere another style rule says that titles should be black. Which color should be displayed in the browser?
The cascade is a set of rules determining which style takes precedence when CSS style rules disagree. But how can this disagreement even happen? You're only supplying that one .css file and it says for example blue! Large websites might employ more than one .CSS file, or sometimes HTML documents contain CSS code right in with the HTML code, in addition to the code in a separate CSS file. Or users might write their own custom style sheets because they prefer a particular typeface, for example. The users want to override your CSS typeface specification (user style rules take precedence over all others). In other words, a browser might have to interpret multiple style rules from different sources, some of them contradictory. The cascade tells the browser how to sort out this conflict—which of multiple CSS specifications should be used.
For today's assignment, practice working with a few CSS style rules. Your task is to edit the Cookbook CSS Stylesheet.css file that you created in this lesson so it displays the recipes according to these style rules:
First, try to write these rules and test them in IE yourself. Then, click the button below to see the code and results.
title { color: FireBrick; display: block; margin-left: 2%; margin-right: 2%; font-family: Helvitica, Arial, sans-serif; } instructions { display:block; margin-left: 5%; margin-right: 5%; margin-bottom: 4%; font-family: Helvitica, Arial, sans-serif; } FireBrick titles and other style values on display
FireBrick titles and other style values on display
Back to top